package cn.ug.analyse.service.impl;

import cn.ug.analyse.bean.request.WithdeawParamBean;
import cn.ug.analyse.bean.response.BaseCountBean;
import cn.ug.analyse.mapper.MemberBalanceMapper;
import cn.ug.analyse.mapper.entity.MemberBalance;
import cn.ug.analyse.service.MemberBalanceService;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.core.ensure.Ensure;
import cn.ug.pay.bean.request.AccountFinanceBillParam;
import cn.ug.pay.bean.response.MemberAccountBean;
import cn.ug.util.Common;
import cn.ug.util.UF;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MemberBalanceServiceImpl implements MemberBalanceService {

    @Resource
    private MemberBalanceMapper memberBalanceMapper;

    private static Logger logger = LoggerFactory.getLogger(MemberBalanceServiceImpl.class);

    @Override
    public DataTable<BaseCountBean> findList(WithdeawParamBean withdeawParamBean) {
        List<BaseCountBean> resultList = new ArrayList<BaseCountBean>();

        if(StringUtils.isBlank(withdeawParamBean.getStartTime())) withdeawParamBean.setStartTime(LocalDate.now().plusDays(-7).toString());
        if(StringUtils.isBlank(withdeawParamBean.getEndTime())) withdeawParamBean.setEndTime(LocalDate.now().plusDays(-1).toString());

        //参数必须传递--起始时间、结束时间
        Ensure.that(withdeawParamBean.getStartTime()).isNull("21000001");
        Ensure.that(withdeawParamBean.getEndTime()).isNull("21000002");
        Ensure.that(withdeawParamBean.getPageType()).isNull("21000004");

        int pageNum = withdeawParamBean.getPageNum();
        int pageSize = withdeawParamBean.getPageSize();
        withdeawParamBean.setPageNum(1);
        withdeawParamBean.setPageSize(100000);
        List<BaseCountBean> list = memberBalanceMapper.findList(withdeawParamBean);
        resultList = findEverydayList(withdeawParamBean);  //每日


        //数据分页
        if(resultList != null && !resultList.isEmpty()) {
            Collections.reverse(resultList);  //倒序排列

            //查询是否分页
            if(withdeawParamBean.getPageType() == 2){
                int total = resultList.size();
                //计算
                int num = (pageNum-1)* pageSize;
                resultList = resultList.stream().skip(num).collect(Collectors.toList());
                List<BaseCountBean> pageList = resultList.stream().limit(pageSize).collect(Collectors.toList());
                return new DataTable<>(pageNum, pageSize, total, pageList);
            }else{
                return new DataTable<>(pageNum, pageSize, resultList.size(), resultList);
            }
        }else {
            return new DataTable<>(pageNum, withdeawParamBean.getPageSize(), 0, new ArrayList<>());
        }
    }

    @Override
    public BigDecimal findTotal(WithdeawParamBean withdeawParamBean) {
        List<BaseCountBean> resultList = new ArrayList<BaseCountBean>();

        if(StringUtils.isBlank(withdeawParamBean.getStartTime())) withdeawParamBean.setStartTime(LocalDate.now().plusDays(-6).toString());
        if(StringUtils.isBlank(withdeawParamBean.getEndTime())) withdeawParamBean.setEndTime(LocalDate.now().toString());

        //参数必须传递--起始时间、结束时间
        Ensure.that(withdeawParamBean.getStartTime()).isNull("21000001");
        Ensure.that(withdeawParamBean.getEndTime()).isNull("21000002");
        withdeawParamBean.setPageNum(1);
        withdeawParamBean.setPageSize(100000);
        resultList = findEverydayList(withdeawParamBean);  //每日
        BigDecimal amount = BigDecimal.ZERO;
        for(BaseCountBean entity: resultList){
            amount = amount.add(entity.getAmount());
        }
        return amount;
    }

    @Override
    public void memberBalanceJob() {
        LocalDate currentDate = LocalDate.now();
        currentDate = currentDate.plusDays(-1);

        Page page = new Page();
        page.setPageSize(1000);
        page.setPageNum(1);
        do{
            //获取所有用户余额
            com.github.pagehelper.Page<AccountFinanceBillParam> pages = PageHelper.startPage(page.getPageNum(),page.getPageSize());
            List<MemberAccountBean> list = memberBalanceMapper.findMemberBalanceList();
            if(list != null && !list.isEmpty()){
                List<MemberBalance> balanceList = new ArrayList<MemberBalance>();
                for(MemberAccountBean account: list){
                    MemberBalance entity = new MemberBalance();
                    entity.setId(UF.getRandomUUID());
                    entity.setDay(currentDate.toString());
                    entity.setMemberId(account.getMemberId());
                    entity.setAmount(account.getUsableAmount());
                    balanceList.add(entity);
                }
                memberBalanceMapper.insert(balanceList);
            }else{
                logger.info("账户统计没有数据了");
                break;
            }
            // 下一页
            page.setPageNum(page.getPageNum() + 1);
        }while(true);
    }

    public void memberBalanceScript(String startTimeString,String endTimeString) {
        LocalDate startTime = LocalDate.parse(startTimeString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endTime = LocalDate.parse(endTimeString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        Page page = new Page();
        page.setPageSize(100000);
        page.setPageNum(1);
        while (startTime.compareTo(endTime) <= 0){

            //获取昨日余额
            BigDecimal amount = memberBalanceMapper.findAmountByDay(startTime.plusDays(-1).toString());
            logger.info("-------昨日余额"+amount);
            //获取收入
            BigDecimal incomeAmount = memberBalanceMapper.findBillTotal(startTime.toString(),1);
            logger.info("-------获取收入"+incomeAmount);
            //获取支出
            BigDecimal payAmount = memberBalanceMapper.findBillTotal(startTime.toString(),2);
            logger.info("-------获取之处"+payAmount);
            logger.info("-----余额---"+amount.add(incomeAmount).subtract(payAmount));
            //获取所有用户余额
            MemberBalance entity = new MemberBalance();
            entity.setId(UF.getRandomUUID());
            entity.setDay(startTime.toString());
            entity.setMemberId(UF.getRandomUUID());
            entity.setAmount(amount.add(incomeAmount).subtract(payAmount));
            List<MemberBalance> balanceList = new ArrayList<MemberBalance>();
            balanceList.add(entity);
            memberBalanceMapper.insert(balanceList);
            startTime = startTime.plusDays(1);
        }
    }

    public List<BaseCountBean> findEverydayList(WithdeawParamBean withdeawParamBean) {
        List<BaseCountBean> resultList = new ArrayList<BaseCountBean>();
        List<BaseCountBean> list = memberBalanceMapper.findList(withdeawParamBean);

        //设置开始时间
        LocalDate startTime = LocalDate.parse(withdeawParamBean.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endTime = LocalDate.parse(withdeawParamBean.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //获取查询出的天数
        int day = Integer.valueOf(Common.until(startTime,endTime) +"") + 1;
        for(int i = 0;i< day;i++) {
            //当前日期时间字符串
            String startTimeString = startTime.toString();
            BaseCountBean entity = new BaseCountBean();
            entity.setDay(startTimeString);
            if(list != null && !list.isEmpty()){
                List<BaseCountBean> filterList = list.stream().filter(o -> o.getDay().contains(startTimeString)).collect(Collectors.toList());
                if(filterList != null && !filterList.isEmpty()){
                    entity.setAmount(filterList.get(0).getAmount());
                }else{
                    entity.setAmount(BigDecimal.ZERO);
                }
            }else{
                entity.setAmount(BigDecimal.ZERO);
            }
            resultList.add(entity);
            startTime = startTime.plusDays(1);
        }
        return resultList;
    }

    public static void main(String[] args) {
        Map<String, Integer> items = new HashMap<>();
        items.put("A", 10);
        items.put("B", 20);
        items.put("C", 30);
        items.put("D", 40);
        items.put("E", 50);
        items.put("F", 60);

        items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

        items.forEach((k,v)->{
            System.out.println("Item : " + k + " Count : " + v);
            if("E".equals(k)){
                System.out.println("Hello E");
            }
        });

    }
}
